//
//  TriggersPluginModule.m
//  Cantrip
//
//  Created by James Callender on Tue Jun 08 2004.
//  Copyright (c) 2004 James Callender. All rights reserved.
//

#import "TriggersPluginModule.h"


@implementation TriggersPluginModule

- (id)init
{
    if (self = [super init]) {

    }
    
    return self;
}

- (NSString *)pluginName
{
    return @"TriggersPlugin";
}

- (NSString *)pluginVersion
{
    return @"0.1";
}

- (void)applicationDidLoadPlugin
{
    [CantripPluginManager() registerPlugin:self forService:InterfaceEventService priority:0];
}

- (BOOL)handleInterfaceEventAction:(NSEvent *)event
{
    id world = [[event window] world];
    id controller = [[event window] windowController];
    NSEnumerator *enumerate;
    NSDictionary *macro;
    
    if ([event type] != NSKeyDown) return NO;
    
    enumerate = [[[world worldData] objectForKey:@"Macros"] objectEnumerator];
    while (macro = [enumerate nextObject]) {
	if ([macro objectForKey:@"Enabled"] && 
	    [[macro objectForKey:@"KeyCode"] intValue] == [event keyCode] && 
	    ([[macro objectForKey:@"ModifierFlags"] intValue] & (NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask)) == 
		([event modifierFlags] & (NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask)))
	{
	    if ([macro objectForKey:@"Script"] && ![[macro objectForKey:@"Script"] isEqualToString:@""])
		[controller performScript:[macro objectForKey:@"Script"] withEnvironment:nil flags:1];
	    return YES;
	}
    }
    
    return NO;
}

@end
